"""
统一配置加载器
"""
import os
import yaml
from pathlib import Path
from typing import Dict, Any, Optional, List
from functools import lru_cache

from ..schemas.service_config import UnifiedConfig

class ConfigLoader:
    """统一配置加载器"""
    
    def __init__(self, config_dir: Optional[Path] = None):
        self.config_dir = config_dir or Path(__file__).parent.parent / "unified"
        self.environment = os.getenv("REDFIRE_ENVIRONMENT", "development")
        
    def load_config(self, environment: Optional[str] = None) -> UnifiedConfig:
        """加载指定环境的配置"""
        env = environment or self.environment
        
        # 1. 加载基础配置
        base_config = self._load_yaml_file("base.yml")
        
        # 2. 加载环境特定配置
        env_config = self._load_yaml_file(f"{env}.yml")
        
        # 3. 加载本地覆盖配置（如果存在）
        local_config = self._load_yaml_file("local.yml", required=False)
        
        # 4. 合并配置
        merged_config = self._merge_configs([base_config, env_config, local_config])
        
        # 5. 环境变量替换
        resolved_config = self._resolve_environment_variables(merged_config)
        
        # 6. 验证配置
        return UnifiedConfig(**resolved_config)
    
    def _load_yaml_file(self, filename: str, required: bool = True) -> Dict[str, Any]:
        """加载YAML配置文件"""
        file_path = self.config_dir / filename
        
        if not file_path.exists():
            if required:
                raise FileNotFoundError(f"配置文件不存在: {file_path}")
            return {}
        
        with open(file_path, 'r', encoding='utf-8') as f:
            content = yaml.safe_load(f) or {}
            
        # 处理继承
        if 'extends' in content:
            parent_file = content.pop('extends')
            parent_config = self._load_yaml_file(parent_file)
            return self._merge_configs([parent_config, content])
        
        return content
    
    def _merge_configs(self, configs: List[Dict[str, Any]]) -> Dict[str, Any]:
        """深度合并多个配置字典"""
        result = {}
        
        for config in configs:
            if not config:
                continue
            result = self._deep_merge(result, config)
        
        return result
    
    def _deep_merge(self, base: Dict[str, Any], override: Dict[str, Any]) -> Dict[str, Any]:
        """深度合并两个字典"""
        result = base.copy()
        
        for key, value in override.items():
            if key in result and isinstance(result[key], dict) and isinstance(value, dict):
                result[key] = self._deep_merge(result[key], value)
            else:
                result[key] = value
        
        return result
    
    def _resolve_environment_variables(self, config: Dict[str, Any]) -> Dict[str, Any]:
        """解析环境变量占位符"""
        import re
        
        def resolve_value(value):
            if isinstance(value, str):
                # 匹配 ${VAR_NAME:default_value} 格式
                pattern = r'\$\{([^}:]+)(?::([^}]*))?\}'
                
                def replacer(match):
                    var_name = match.group(1)
                    default_value = match.group(2) or ""
                    return os.getenv(var_name, default_value)
                
                return re.sub(pattern, replacer, value)
            elif isinstance(value, dict):
                return {k: resolve_value(v) for k, v in value.items()}
            elif isinstance(value, list):
                return [resolve_value(item) for item in value]
            else:
                return value
        
        return resolve_value(config)

@lru_cache()
def get_config(environment: Optional[str] = None) -> UnifiedConfig:
    """获取配置实例（缓存）"""
    loader = ConfigLoader()
    return loader.load_config(environment)

def reload_config():
    """重新加载配置（清除缓存）"""
    get_config.cache_clear()
